package org.yjh.controller;


import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yjh.pojo.Collections;
import org.yjh.pojo.Goods;
import org.yjh.pojo.User;
import org.yjh.service.LoginService;
import org.yjh.tool.GetUrl;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping(produces = "text/html;charset=UTF-8")
public class Platform {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/code")
    @ResponseBody
    public String analysisCode(String code,HttpServletRequest req){
        String s = loginService.analysisCode(code, req);
        return s;
    }

    /**
     * 用户登陆
     * @param u
     * @return
     */
    @RequestMapping("/user/login")
    @ResponseBody
    public String getLogin(User u){

        // 判断用户与密码
        User user = loginService.analysisUser(u.getUname(),u.getPassword());

        return  JSONObject.toJSONString(user);
    }

    /**
     * 用户注册
     */
    @RequestMapping("/user/registered")
    @ResponseBody
    public String registered(User u){

       return loginService.registeredUser(u);

    }
    /**
     * 更新验证码图
     * @param resp
     */
    @RequestMapping("/getCode")
    public void  getCoded(HttpServletResponse resp){
        int width=100;
        int height=50;
        //1、创建图片对象，用于创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //【第三个参数为图片输出格式】
        //2、美化图片
        //2.1填充背景色
        Graphics g = image.getGraphics();//获取画笔对象
        g.setColor(Color.PINK);//设置画笔颜色
        g.setFont(new Font("黑体",Font.BOLD,24));
        g.fillRect(0,0,width,height);//在图片中的填充范围

        //2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);//在图片中画边框，边框占1像素大小

        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        //生成随机角标【随机生产数去取str字符串的某个索引】
        Random ran = new Random();
        String code="";
        for (int i = 1; i <=4 ; i++) {
            int index =ran.nextInt(str.length());//在长度范围内产生一个随机的数
            char ch = str.charAt(index);//从随机数获取字符
            code += ch;
            //2.3写验证码 rand.nextInt(1)+width/5*i
            Random rand = new Random();
            int a = width/4*(i-1); // 0 25 50 75
            int r = (rand.nextInt(20)+a);
            int x = r > 85? 85 : r;  //0-20-45-70-85
            System.out.println(x);
            g.drawString(ch+"",x,height/2);//插入数据到图片
            //【第一个为数据，第二、三个参数为数据位置】
        }

        //2.4画干扰线
        g.setColor(Color.GREEN);
        //随机生产坐标点
        for (int i = 0; i < 5; i++) {
            int x1=ran.nextInt(width);
            int x2=ran.nextInt(width);
            int y1=ran.nextInt(height);
            int y2=ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);//根据指标画线
        }

        //3、将图片输出到页面展示
        try {
            Cookie repCode = new Cookie("code", code);
            resp.addCookie(repCode);
            ImageIO.write(image,"jpg",resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //【这个操作会把响应返回了，该代码不能再次去进行操作响应】【将照片以jpg的形式写到resp的流中，响应后会自动渲染到<img>标签中】
    }


    /**
     * 获取所有商品
     */
    @RequestMapping("/intercept/goods/getlistdata")
    @ResponseBody
    public String getListData(User u,String gtype){

        // 根据类型进行匹配获取商品信息
        System.out.println(gtype);

        List<Goods> listGoods = loginService.getListGoods(gtype);

        System.out.println("返回的信息："+JSONObject.toJSONString(listGoods));
        return JSONObject.toJSONString(listGoods);
    }

    /**
     * 判断是否管理员
     */
    @RequestMapping("/intercept/goods/isroot")
    @ResponseBody
    public String isRoot(User u){

        // 判断utype是否为0或1
        return String.valueOf(loginService.isRoot(u));
    }

    /**
     * 通过搜索查找内容
     */
    @RequestMapping("/intercept/goods/asguname")
    @ResponseBody
    public String getGoodsByGname(Goods g){

        return JSONObject.toJSONString(loginService.getGoodsByGname(g));
    }

    /**
     * 按条件搜索用户信息
     */
    @RequestMapping("/intercept/user/getuserasconditions")
    @ResponseBody
    public String getUserAsConditions(User u, @RequestParam(value = "suid", required=false)String suid){
        // suid是搜索时的id，User对象的id是用户在拦截器中验证用的
//        System.out.println("进");
//        System.out.println(u);
        if(suid != ""){
            u.setUid(Integer.valueOf(suid)); // 所以需要用suid对User对象中的uid进行覆盖
        }else{
            u.setUid(0);
        }
//        System.out.println(loginService.getUserAsConditions(u));
        return JSONObject.toJSONString(loginService.getUserAsConditions(u));
    }

    /**
     * 按条件搜索商品信息【指定用户查询的】
     */
    @RequestMapping("/intercept/goods/getgoodsasconditions")
    @ResponseBody
    public String getGoodsAsConditions(Goods g){
        System.out.println("执行");
        System.out.println("goods："+g);
        return JSONObject.toJSONString(loginService.getGoodsAsConditions(g));
    }

    /**
     * 删除用户cookie
     */
    @RequestMapping("/intercept/user/deleteusercookie")
    @ResponseBody
    public String deleteUserCookie(User u){
        loginService.deleteUserCookie(u);
        return "1";
    }

    /**
     * 根据gid获取商品信息
     */
    @RequestMapping("/intercept/goods/getgoodsasid")
    @ResponseBody
    public String  getGoodsAsId(User u ,Goods g){
        return JSONObject.toJSONString(loginService.getGoodsAsId(g));
    }

    /**
     * 根据gid删除商品
     */
    @RequestMapping("/intercept/goods/deletegoods")
    @ResponseBody
    public String deleteGoods(User u,String choose,Goods g){

        // 根据choose中的gid删除商品
        loginService.deleteGoods(u,choose);
        // 更新
        g.setState(999);// 查询所有状态的
        return JSONObject.toJSONString(loginService.getGoodsAsConditions(g));
    }

    /**
     * 添加商品
     */
    @RequestMapping(value = "/goods/setgoods",method = RequestMethod.POST)
    @ResponseBody
    public String setGoods(User u,Goods g,@RequestPart("file") MultipartFile file){
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        String[] split = originalFilename.split("\\."); // 要用转义后的

        //保存文件
        try {
            GetUrl getUrl = new GetUrl();
            String url = getUrl.getUrl();
            url += "."+split[1];  // 拼接照片尾缀

            // 保存到vue包那里  this.getClass().getClassLoader().getResource("./img")+"/"+g.getGname()+"."+split[1])
            file.transferTo(new File("D:\\高级语言笔记\\二手平台\\school_platform\\src\\assets\\"+url));
            // 然后将信息存在数据库
            loginService.setGoods(g,url);
            return  "1";
        } catch (IOException e) {
            e.printStackTrace();
        }
       return "0";
    }

    /**
     * 修改商品信息
     */
    @RequestMapping("/intercept/goods/updategoods")
    @ResponseBody
    public String upDateGoods(Goods g){
        loginService.upDateGoods(g);
        return "1";
    }

    /**
     * 根据collection的值进行删除或添加数据
     */
    @RequestMapping("/intercept/collection/setcollection")
    @ResponseBody
    public String setCollections(Collections c, boolean collection){


        return loginService.setCollections( c,collection);
    }

    /**
     * 查询该用户是否收藏了商品
     */
    @RequestMapping("/intercept/collection/selectcollections")
    @ResponseBody
    public String selectCollections(Collections c){
        return JSONObject.toJSONString(loginService.selectCollections(c));
    }

    /**
     * 根据uid去判断收藏表中有收藏的gid,然后查询商品表
     */
    @RequestMapping("/intercept/collections/getgoodsforcollections")
    @ResponseBody
    public String getGoodsForCollections(Goods g){
        return JSONObject.toJSONString(loginService.getGoodsForCollections(g));
    }
}



